package cn.xuewenbao.eduorder.service.impl;

import cn.xuewenbao.edu.entity.ColumnData;
import cn.xuewenbao.edu.entity.Course;
import cn.xuewenbao.edu.entity.LikeContent;
import cn.xuewenbao.edu.entity.vo.MyFavoriteVo;
import cn.xuewenbao.edu.entity.vo.MyLikeOrFavoriteContentVo;
import cn.xuewenbao.edu.service.*;
import cn.xuewenbao.eduorder.entity.Eduorder;
import cn.xuewenbao.eduorder.mapper.EduorderMapper;
import cn.xuewenbao.eduorder.service.EduorderService;
import cn.xuewenbao.eduorder.utils.OrderNoUtil;
import cn.xuewenbao.ucenter.entity.Member;
import cn.xuewenbao.ucenter.entity.VipType;
import cn.xuewenbao.ucenter.service.MemberService;
import cn.xuewenbao.ucenter.service.VipService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-06-30
 */
@Service
public class EduorderServiceImpl extends ServiceImpl<EduorderMapper, Eduorder> implements EduorderService {
    private final String ColumnTypeCourse = "2";
    @Autowired
    private MemberService memberService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private VipService vipService;
    @Autowired
    private ColumnTypeService columnTypeService;
    @Autowired
    private ColumnDataService columnDataService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private LikeContentService likeContentService;
    @Autowired
    private FavoriteService favoriteService;

    //生成课程订单
    @Override
    public Result<String> createCourseOrder(String courseId, String mobileByToken) {
        Result<String> result = new Result<>();
        //获取用户信息
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("mobile", mobileByToken);
        Member member = memberService.getOne(memberQueryWrapper);

        //获取课程
        Course course = courseService.getById(courseId);

        //判断课程订单是否已创建且支付
        QueryWrapper<Eduorder> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("member_id", member.getId()).eq("content_id", courseId).eq("column_type", ColumnTypeCourse);
        orderWrapper.eq("status", 1).last("LIMIT 1");
        Eduorder paidOrder = baseMapper.selectOne(orderWrapper);
        if (paidOrder != null) {
            result.setSuccess(false);
            result.setMessage("已购买该课程");
            return result;
        }

        Eduorder eduorder = new Eduorder();
        eduorder.setOrderNo(OrderNoUtil.getOrderNo());//订单号
        eduorder.setContentId(courseId); //课程id
        eduorder.setColumnType(ColumnTypeCourse);
        eduorder.setContentType(null);
        eduorder.setContentTitle(course.getTitle());
        eduorder.setContentCover(course.getCover());
        eduorder.setTotalFee(course.getPrice());
        eduorder.setMemberId(member.getId());
        eduorder.setMobile(mobileByToken);
        eduorder.setUserName(member.getUsername());
        eduorder.setStatus(0);  //订单状态（0：未支付 1：已支付）
        eduorder.setPayType(0);  //支付类型, 1:微信, 2:支付宝, 0:未支付
        baseMapper.insert(eduorder);
        result.setResult(eduorder.getOrderNo());
        return result;
    }

    //生成会员订单
    @Override
    public Result<String> createVipOrder(String vipTypeId, String mobileByToken) {
        Result<String> result = new Result<>();
        //获取用户信息
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("mobile", mobileByToken);
        Member member = memberService.getOne(memberQueryWrapper);
        //获取vipType, 根据vipTypeId
        Result<VipType> vipTypeResult = vipService.getVipTypeInfo(vipTypeId);
        if (!vipTypeResult.isSuccess()) {
            result.setSuccess(false);
            result.setMessage("会员类型错误");
            return result;
        }
        VipType vipType = vipTypeResult.getResult();
        //生成订单
        Eduorder eduorder = new Eduorder();
        eduorder.setOrderNo(OrderNoUtil.getOrderNo());//订单号
        eduorder.setContentId(null);
        eduorder.setContentType(vipTypeId);
        eduorder.setContentTitle(vipType.getName());
        eduorder.setContentCover(null); //todo 学问宝会员图片
        eduorder.setTotalFee(vipType.getPrice());
        eduorder.setMemberId(member.getId());
        eduorder.setMobile(mobileByToken);
        eduorder.setUserName(member.getUsername());
        eduorder.setStatus(0);  //订单状态（0：未支付 1：已支付）
        eduorder.setPayType(0);  //支付类型, 1:微信, 2:支付宝, 0:未支付
        baseMapper.insert(eduorder);

        result.setResult(eduorder.getOrderNo());
        return result;
    }

    //查找用户在专栏的购买记录
    @Override
    public Result<?> getPurchasedList(String userId, String columnType) {
        List<MyFavoriteVo> voList = new ArrayList<>();
        //获取用户在专栏下所有已支付的订单记录
        QueryWrapper<Eduorder> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", userId).eq("column_type", columnType).eq("status", 1);
        List<Eduorder> purchasedList = baseMapper.selectList(wrapper);
        //根据每一条已支付的订单记录, 获取更全的vo信息
        for (Eduorder order : purchasedList) {
            //获取 MyFavoriteVo的 contentId userId columnType
            MyFavoriteVo vo = new MyFavoriteVo();
            BeanUtils.copyProperties(order, vo);
            vo.setColumnType(columnType);
            //获取 MyFavoriteVo的 title cover viewCount
            String tableName = columnTypeService.getColumnTypeById(columnType);
            if (tableName == null) {
                return Result.error("订单的专栏类型columnType不正确");
            }
            MyLikeOrFavoriteContentVo contentVo = columnTypeService.selectMyLikeOrFavoriteContent(order.getContentId(), tableName);
            if (contentVo == null) {    //已支付订单记录的原内容查找不到 (已删除)
                continue;   //查找下一个订单记录
            }
            BeanUtils.copyProperties(contentVo, vo);    //soure不能为 null
            //获取 MyFavoriteVo的 likeCount favoriteCount commentCount;
            QueryWrapper<ColumnData> columnDataWrapper = new QueryWrapper<>();
            columnDataWrapper.eq("content_id", order.getContentId()).eq("column_type", columnType);
            ColumnData data = columnDataService.getOne(columnDataWrapper);
            if (data == null) { //根据订单记录, 原内容的数据查找不到 (已删除)
                continue;   //查找下一个订单记录
            }
            BeanUtils.copyProperties(data, vo);
            //获取 MyFavoriteVo的 commentCount isLike isFavorite;
            Long count = commentService.getCommentCount(order.getContentId(), columnType);
            vo.setCommentCount(count);
            boolean isFavorite = favoriteService.hasFavoriteOne(userId, order.getContentId(), columnType).isSuccess();
            vo.setIsFavorite(isFavorite);
            boolean isLike = likeContentService.hasLikeOne(userId, order.getContentId(), columnType).isSuccess();
            vo.setIsLike(isLike);
            voList.add(vo);
        }
        return Result.OK("获取已购列表成功！", voList);
    }
}
